package cn.spring.framework.redis.excutor;

import cn.spring.framework.redis.context.RedisCacheContext;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author xingkong
 * @Title: AsyncCacheExecutor
 * @Description: 异步任务执行
 * @date 2021/11/12 17:32
 */
public class AsyncCacheExecutor<T> implements CacheExecutor<T> {
    private ExecutorService executorService = ExecutorUtils.getExecutorService();

    public AsyncCacheExecutor() {
    }

    public AsyncCacheExecutor(ExecutorService executorService) {
        this.executorService = executorService;
    }

    @Override
    public Future<T> executor(CacheTask<T> task) {
        FutureAdapter<T> futureAdapter = new FutureAdapter<>(executorService.submit(task));
        RedisCacheContext.getContext().setFuture(futureAdapter);
        return futureAdapter;
    }

    static class ExecutorUtils {
        /**
         * 默认线程池
         */
        private static ExecutorService executorService = Executors.newCachedThreadPool();

        public static ExecutorService getExecutorService() {
            return executorService;
        }
    }

}
